package work.chenbo.mybatis.customize.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author ChenBo
 * @className XmlMapperBuilder
 * @date 2020/12/23
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration){
        this.configuration = configuration;
    }

    public void parseMapper(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespaces = rootElement.attributeValue("namespaces");
        List<Element> elementList = rootElement.selectNodes("select");
        for (Element element : elementList){
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            String key = namespaces + "." + id;
            mappedStatement.setId(id);
            mappedStatement.setSql(sql);
            mappedStatement.setParameterType(getClassType(parameterType));
            mappedStatement.setResultType(getClassType(resultType));
            Map<String, MappedStatement> mappedStatementMap = configuration.getMappedStatementMap();
            mappedStatementMap.put(key,mappedStatement);
        }

    }

    private Class<?> getClassType(String classType) throws ClassNotFoundException {
        if(classType!=null && classType!=""){
            return Class.forName(classType);
        }
        return null;
    }
}
